package com.sychip.fhc.app.wsn.screen

import android.content.Intent
import android.content.res.Configuration
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.tween
import androidx.compose.animation.expandVertically
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.shrinkVertically
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.layout.wrapContentWidth
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Check
import androidx.compose.material.icons.outlined.Apps
import androidx.compose.material.icons.outlined.ArrowDropDown
import androidx.compose.material.icons.outlined.Settings
import androidx.compose.material.icons.outlined.SettingsSuggest
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.DividerDefaults
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.MaterialTheme.colorScheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Switch
import androidx.compose.material3.SwitchDefaults
import androidx.compose.material3.Text
import androidx.compose.material3.rememberModalBottomSheetState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.core.content.FileProvider
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.navigation.NavHostController
import androidx.navigation.compose.rememberNavController
import com.fhc.base.EventBusSubGInfo
import com.fhc.base.LocalManager
import com.fhc.base.LocalManager.stringResource
import com.fhc.base.isTablet
import com.fhc.view.FhcBottomSheet
import com.fhc.view.FhcSlider
import com.fhc.view.rememberFhcBottomSheetVisibleState
import com.sychip.fhc.IS_DEBUG
import com.sychip.fhc.app.todo.R
import com.sychip.fhc.app.wsn.nav.WsnNavigationItem
import com.sychip.fhc.app.wsn.screen.components.SubGSettingCmd
import com.sychip.fhc.app.wsn.screen.components.SubGSettingView
import com.sychip.fhc.lib.base.Chinese
import com.sychip.fhc.lib.base.ENGLISH
import com.sychip.fhc.lib.base.FhcTopAppBar
import com.sychip.fhc.lib.base.JAPANESE
import kotlinx.coroutines.CoroutineScope
import timber.log.Timber
import java.io.File
import java.util.Locale


val startP = 20.dp
val widthP = 36.dp
val spaceP = 16.dp
val rightP = startP + widthP + spaceP

@Composable
@OptIn(ExperimentalMaterial3Api::class, ExperimentalLayoutApi::class)
fun WsnSettingsScreen(navController: NavHostController = rememberNavController()) {
    val visibleSubGState = rememberFhcBottomSheetVisibleState()
    val coroutineScope: CoroutineScope = rememberCoroutineScope()
    val navBackStackEntry = remember { navController.currentBackStackEntry }
    val viewModel: WsnSettingsViewModel = navBackStackEntry?.let { hiltViewModel(it) } ?: hiltViewModel()
    val usbOnline by viewModel.usbOnline.collectAsStateWithLifecycle()
    val subG by viewModel.subG.collectAsStateWithLifecycle()

    LaunchedEffect(usbOnline) {
        if (!usbOnline) {
            visibleSubGState.value = false
        }
    }
    Scaffold(
        modifier = Modifier.fillMaxSize(),
        topBar = {
            FhcTopAppBar(
                title = WsnNavigationItem.NavItem_Setting.label,
                actions = {},
            )
        }
    ) { innerPadding ->
        Box(modifier = Modifier.padding(top = innerPadding.calculateTopPadding()).fillMaxWidth()) {
            SettingsContent(viewModel=viewModel, modifier = Modifier.fillMaxSize(), showSubGEditState = visibleSubGState)
            // 保存原始值
            val oldSubg = subG.copy()
            val editSubG = remember(subG) { mutableStateOf(subG) }
            val subGCmd = remember { mutableStateOf(SubGSettingCmd.INIT) }
            val sheetSubGState = rememberModalBottomSheetState(skipPartiallyExpanded = true,
                confirmValueChange = {
                    true
                } // 关键！false阻止所有状态变更
            )

            FhcBottomSheet(
                title = stringResource(R.string.wsn_subg_setting),
                sheetState = sheetSubGState,
                visibleState = visibleSubGState,
                coroutineScope = coroutineScope,
                showActionYes = true,
                onActionYes = {
                    subGCmd.value = SubGSettingCmd.SAVE
                    false
                },
                onDismiss = {
                    // 在取消时恢复原始值
                    editSubG.value = oldSubg
                }
            ) {
                SubGSettingView(editSubG, subGCmd, onSave = {it, hasError->
                    Timber.e("SubGSettingView  hasError:%s  channel :%s  port:%s   panId:%s  encryption:%s  key:%s", hasError,it.channel, it.port, it.panId, it.encryption, it.key)
                    if(hasError){
                        false
                    }else{
                        viewModel.saveSubGInfo(it)
                        visibleSubGState.value = false
                        true
                    }
                })
            }
        }
    }
}


@Composable
@OptIn(ExperimentalMaterialApi::class)
private fun SettingsContent(
    modifier: Modifier = Modifier, viewModel: WsnSettingsViewModel = hiltViewModel(),
    showSubGEditState : MutableState<Boolean> = remember { mutableStateOf(false) },
) {


    val usbOnline by viewModel.usbOnline.collectAsStateWithLifecycle()
    LaunchedEffect(usbOnline) {
        if(usbOnline){
            viewModel.requestSubgInfo()
        }
    }


    Column(modifier.fillMaxSize().verticalScroll(rememberScrollState())) {


            Spacer(Modifier.height(8.dp))
//            LanguageSection()
            LanguageDetailSection()

            val appSettingFlow  by viewModel.appSettingFlow.collectAsStateWithLifecycle()
            RssiSection(appSettingFlow.avgNums, onAvgNum =  {
                viewModel.setAvgNum(it)
            }, rssiMins = appSettingFlow.rssiMins, onRssiMins = {
                viewModel.setRssiMinutes(it)
            })
            val subG by viewModel.subG.collectAsStateWithLifecycle()
            if(usbOnline || IS_DEBUG) {
                SubGSection(true, subG = subG, showSubGEditState= showSubGEditState)
            }


            val context = LocalContext.current
            val intent = remember {
                Intent(Intent.ACTION_VIEW).apply {
                    // 在预览模式下context.filesDir可能为null，需要进行空安全检查
                    val logDir = context.getExternalFilesDir("logs") ?:
                    context.filesDir?.resolve("logs")?.apply { mkdirs() } ?:
                    // 如果context.filesDir为null（如在预览模式下），则使用临时目录
                    File(context.cacheDir, "logs").apply { mkdirs() }

                    val uri = FileProvider.getUriForFile(
                        context,
                        "${context.packageName}.provider",
                        logDir
                    )
                    setDataAndType(uri, "resource/folder")
                    addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
                }
            }
            AppSection(appSettingFlow.logEnable, onEnableLog =  {
                viewModel.setLogEnable(it)
            }, intent)

    }
}



@Preview(showBackground = true,widthDp = 800)
@Composable
private fun SubGSection(usbOnline:Boolean = false, subG: EventBusSubGInfo = EventBusSubGInfo(),
                        showSubGEditState : MutableState<Boolean> = remember { mutableStateOf(false) }) {

    Column(modifier = Modifier.fillMaxWidth()) {
        SubGDetailSection(usbOnline = usbOnline, subG = subG, rightP, rightBottomContent ={
            IconButton(
                modifier = Modifier.height(widthP),
                onClick = {
                    showSubGEditState.value = true
                }) {
                Icon(Icons.Outlined.Settings, null)
            }
        })

    }
}

//
//@Composable
//private fun LanguageSection() {
//
//    val currentLocale = LocalManager.currentLocale.collectAsStateWithLifecycle()
//    val context = LocalContext.current
//    val startP = 20.dp
//    val widthP = 36.dp
//    val spaceP = 16.dp
//
//    Box(modifier = Modifier.fillMaxWidth()){
//        Card(
//            colors = CardDefaults.cardColors(containerColor = Color.White.copy(alpha = 0.15f)),
//            shape = RoundedCornerShape(12.dp), // 自定义圆角大小
//            modifier = Modifier.fillMaxWidth().padding(16.dp)
//        ) {
//            val isLangExpanded = remember { mutableStateOf(false) }
//            Row(
//                modifier = Modifier.padding(top = 10.dp, bottom = 10.dp, start = startP).clickable(
//                    onClick = {
//                        isLangExpanded.value = !isLangExpanded.value
//                    }
//                ),
//                verticalAlignment = Alignment.CenterVertically
//            ) {
//                Icon(
//                    painterResource(id = if(currentLocale.value.language == Locale.JAPANESE.language)  R.drawable.ic_lang_jp_en  else R.drawable.ic_lang_en_jp),
//                    null,
//                    Modifier.size(widthP),
//                    colorScheme.primary
//                )
//                Spacer(modifier = Modifier.width(spaceP))
//                Row(modifier = Modifier.fillMaxWidth().weight(1f)) {
//                    Text(
//                        modifier = Modifier.weight(1f).align(alignment = Alignment.CenterVertically),
//                        text =  swapStringParts(if(currentLocale.value.language == Locale.JAPANESE.language) JAPANESE else ENGLISH),
//                        style = MaterialTheme.typography.titleSmall,
//                        color = colorScheme.onPrimaryContainer,
//                        fontWeight = FontWeight.ExtraBold
//                    )
//                }
//                LanguageSwitchMenu(
//                    isLangExpanded,
//                    {locale->
//                        Timber.i("LanguageMenu:%s", locale)
//                        LocalManager.setAppLocale(context,locale.language)
//
//                    }
//                )
////                IconButton(
////                    modifier = Modifier.padding(end = 6.dp).height(widthP).align(alignment = Alignment.CenterVertically),
////                    onClick = {
////                        if(currentLocale.value.language == Locale.JAPANESE.language) LocalManager.setAppLocale(context,Locale.ENGLISH.language)
////                        else LocalManager.setAppLocale(context,Locale.JAPANESE.language)
////                    }) {
////                    Icon(
////                        painterResource(id = if(currentLocale.value.language == Locale.JAPANESE.language)  R.drawable.ic_lang_jp_en  else R.drawable.ic_lang_en_jp),
////                        null
////                    )
////                }
//            }
//        }
//
//
//    }
//}

//private fun swapStringParts(input: String): String {
//    val parts = input.split(" ").filter { it.isNotBlank() }
//    return if (parts.size == 2) "${parts[1]} ${parts[0]}" else input
//}
@Composable
private fun SubGDetailSection(usbOnline:Boolean = false, subG: EventBusSubGInfo? = EventBusSubGInfo(),
                              leftRightPadding: Dp = 0.dp, rightBottomContent: @Composable () -> Unit = {}) {


    val isExpanded = remember { mutableStateOf(usbOnline) }
    val rotation = remember { Animatable(0f) }

    // 动画启动副作用
    LaunchedEffect(isExpanded.value) {
        val targetRotation = if (isExpanded.value) 180f else 0f
        rotation.animateTo(
            targetRotation,
            animationSpec = tween(durationMillis = 300)
        ) {
        }
    }
    var items: List<Pair<String, String>> = listOf(
        stringResource(R.string.wsn_subg_channel) to stringResource(R.string.wsn_usb_no_data),
        stringResource(R.string.wsn_subg_port) to stringResource(R.string.wsn_usb_no_data),
        stringResource(R.string.wsn_subg_pan) to stringResource(R.string.wsn_usb_no_data),
        stringResource(R.string.wsn_subg_encryption) to stringResource(R.string.wsn_usb_no_data)
    )
    if (subG != null && usbOnline) {
        items = listOf(
            stringResource(R.string.wsn_subg_channel) to subG.channel,
            stringResource(R.string.wsn_subg_port) to subG.port,
            stringResource(R.string.wsn_subg_pan) to subG.panId,
            stringResource(R.string.wsn_subg_encryption) to if(subG.encryption) stringResource(R.string.wsn_subg_encryption_enable) else stringResource(R.string.wsn_subg_encryption_disable)
        )
    }
    Box(modifier = Modifier.fillMaxWidth()){
        Card(
            colors = CardDefaults.cardColors(containerColor = Color.White.copy(alpha = 0.15f)),
            shape = RoundedCornerShape(12.dp), // 自定义圆角大小
            modifier = Modifier.fillMaxWidth().padding(spaceP)
        ) {
            Row(
                modifier = Modifier.padding(top = 10.dp, bottom = 10.dp, start = startP).clickable(
                    onClick = {isExpanded.value = !isExpanded.value}
                ),
                verticalAlignment = Alignment.CenterVertically
            ) {
                Image(
                    modifier = Modifier.size(widthP),
                    painter = painterResource(id = R.drawable.ic_sensor2),
                    colorFilter = ColorFilter.tint(colorScheme.primary),
                    contentDescription = null,
                )
                Spacer(modifier = Modifier.width(spaceP))
                Row(modifier = Modifier.fillMaxWidth().weight(1f)) {
                    Text(
                        modifier = Modifier.weight(1f).align(alignment = Alignment.CenterVertically),
                        text = stringResource(R.string.wsn_subg_setting),
                        style = MaterialTheme.typography.titleSmall,
                        color = colorScheme.onPrimaryContainer,
                        fontWeight = FontWeight.ExtraBold
                    )

                    Text(
                        modifier = Modifier.padding(end = spaceP).align(alignment = Alignment.CenterVertically),
                        text = if (usbOnline) {
                            stringResource(R.string.wsn_usb_online)
                        } else {
                            stringResource(R.string.wsn_usb_offline)
                        },
                        style = MaterialTheme.typography.bodySmall,
                        color = colorScheme.onPrimaryContainer.copy(alpha = if (!usbOnline) 0.5f else 1f)
                    )
                }

                    IconButton(
                        modifier = Modifier.padding(end = 6.dp).height(widthP).align(alignment = Alignment.CenterVertically),
                        onClick = {
                            isExpanded.value = !isExpanded.value
                        }) {
                        Icon(Icons.Outlined.ArrowDropDown, null, tint = Color.White, modifier = Modifier.size(32.dp).graphicsLayer {
                            rotationZ = rotation.value
                        })
                    }

            }
            AnimatedVisibility(
                visible = isExpanded.value,
                enter = expandVertically() + fadeIn(),
                exit = shrinkVertically() + fadeOut()
            ) {
                HorizontalDivider(modifier = Modifier.padding(start = 16.dp, end = 16.dp))
                Column(
                    modifier = Modifier.padding(start = leftRightPadding, end = leftRightPadding, top = 16.dp, bottom = 16.dp)
                ) {
                    items.forEach { (label, value) ->
                        CardItemRow(label, value)
                        HorizontalDivider(
                            modifier = Modifier.padding(vertical = 8.dp),
                            thickness = DividerDefaults.Thickness,
                            color = DividerDefaults.color
                        )
                    }
                }
            }

        }
        if(isExpanded.value && usbOnline){
            Box(modifier = Modifier.align(Alignment.BottomEnd).wrapContentSize().padding(end = 20.dp, bottom = 32.dp)) {
                rightBottomContent()
            }
        }

    }
}


@Preview(showBackground = true,widthDp = 800)
@Composable
private fun LanguageDetailSection() {
    val isExpanded = remember { mutableStateOf(true) }

//    val currentLocale = LocalManager.currentLocale.collectAsStateWithLifecycle()
//    val isSystemLocale = LocalManager.isSystemLocale.collectAsStateWithLifecycle()

    val rotation = remember { Animatable(0f) }

    // 动画启动副作用
    LaunchedEffect(isExpanded.value) {
        val targetRotation = if (isExpanded.value) 180f else 0f
        rotation.animateTo(
            targetRotation,
            animationSpec = tween(durationMillis = 300)
        ) {
        }
    }
    val items: List<Pair<String, String>> = listOf(
        stringResource(R.string.wsn_lang_follow_system) to "",
        JAPANESE to Locale.JAPANESE.language,
        ENGLISH to Locale.ENGLISH.language,
        Chinese to Locale.CHINESE.language,
    )

    Box(modifier = Modifier.fillMaxWidth()){
        Card(
            colors = CardDefaults.cardColors(containerColor = Color.White.copy(alpha = 0.15f),
                contentColor = Color.White),
            shape = RoundedCornerShape(12.dp), // 自定义圆角大小
            modifier = Modifier.fillMaxWidth().padding(spaceP)
        ) {
            Row(
                modifier = Modifier.padding(top = 10.dp, bottom = 10.dp, start = startP,end = 6.dp).clickable(
                    onClick = {isExpanded.value = !isExpanded.value}
                ),
                verticalAlignment = Alignment.CenterVertically
            ) {
                Icon(
                    painterResource(id =
                         R.drawable.ic_lang
                    ),
                    null,
                    Modifier.size(widthP),
                    colorScheme.primary
                )


                Spacer(modifier = Modifier.width(spaceP))
                Row(modifier = Modifier.fillMaxWidth().weight(1f)) {
                    Text(
                        modifier = Modifier.weight(1f).align(alignment = Alignment.CenterVertically),
                        text = stringResource(R.string.wsn_lang_setting),
                        style = MaterialTheme.typography.titleSmall,
                        color = colorScheme.onPrimaryContainer,
                        fontWeight = FontWeight.ExtraBold
                    )
                }
                IconButton(
                    modifier = Modifier.height(widthP).align(alignment = Alignment.CenterVertically),
                    onClick = {
                        isExpanded.value = !isExpanded.value
                    }) {
                    Icon(Icons.Outlined.ArrowDropDown, null, tint = Color.White, modifier = Modifier.size(32.dp).graphicsLayer {
                        rotationZ = rotation.value
                    })
                }
            }
            AnimatedVisibility(
                visible = isExpanded.value,
                enter = expandVertically() + fadeIn(),
                exit = shrinkVertically() + fadeOut()
            ) {
                HorizontalDivider(modifier = Modifier.padding(start = 16.dp, end = 16.dp))
                Column(
                    modifier = Modifier.padding(start = rightP, end = rightP, top = 16.dp, bottom = 16.dp)
                ) {
                    items.forEach { (label, language) ->
                        LanguageItemRow(label, language)
                        HorizontalDivider(
                            modifier = Modifier.padding(vertical = 8.dp),
                            thickness = DividerDefaults.Thickness,
                            color = DividerDefaults.color
                        )
                    }
                }
            }

        }
    }
}

@Preview(showBackground = true,widthDp = 800)
@Composable
private fun RssiSection(avgNum:Int = 4, onAvgNum: (Int) -> Unit ={}, rssiMins:Int = 5, onRssiMins: (Int) -> Unit ={}) {
    val isExpanded = remember { mutableStateOf(true) }
//
    val rotation = remember { Animatable(0f) }

    // 动画启动副作用
    LaunchedEffect(isExpanded.value) {
        val targetRotation = if (isExpanded.value) 180f else 0f
        rotation.animateTo(
            targetRotation,
            animationSpec = tween(durationMillis = 300)
        ) {
        }
    }


    Box(modifier = Modifier.fillMaxWidth()){
        Card(
            colors = CardDefaults.cardColors(containerColor = Color.White.copy(alpha = 0.15f),
            contentColor = Color.White),
            shape = RoundedCornerShape(12.dp), // 自定义圆角大小
            modifier = Modifier.fillMaxWidth().padding(spaceP)
        ) {
            Row(
                modifier = Modifier.padding(top = 10.dp, bottom = 10.dp, start = startP,end = 6.dp).clickable(
                    onClick = {isExpanded.value = !isExpanded.value}
                ),
                verticalAlignment = Alignment.CenterVertically
            ) {
//                CircleTextView(text = "RSSI", sizeDp = widthP, backgroundColor = colorScheme.onPrimaryContainer.copy(alpha = 0.3f))
                Icon(
                    Icons.Outlined.SettingsSuggest, null, Modifier.size(widthP), colorScheme.primary
                )
                Spacer(modifier = Modifier.width(spaceP))
                Row(modifier = Modifier.fillMaxWidth().weight(1f)) {
                    Text(
                        modifier = Modifier.weight(1f).align(alignment = Alignment.CenterVertically),
                        text = stringResource(R.string.wsn_rssi_setting),
                        style = MaterialTheme.typography.titleSmall,
                        color = colorScheme.onPrimaryContainer,
                        fontWeight = FontWeight.ExtraBold
                    )
                }
                IconButton(
                    modifier = Modifier.height(widthP).align(alignment = Alignment.CenterVertically),
                    onClick = {
                        isExpanded.value = !isExpanded.value
                    }) {
                    Icon(Icons.Outlined.ArrowDropDown, null, tint = Color.White, modifier = Modifier.size(32.dp).graphicsLayer {
                        rotationZ = rotation.value
                    })
                }
            }
            val config = LocalConfiguration.current
            AnimatedVisibility(
                visible = isExpanded.value,
                enter = expandVertically() + fadeIn(),
                exit = shrinkVertically() + fadeOut()
            ) {
                HorizontalDivider(modifier = Modifier.padding(start = 16.dp, end = 16.dp))
                Column(modifier = Modifier.padding(start = rightP, end = rightP, top = 16.dp, bottom = 16.dp)) {

                    if (config.orientation == Configuration.ORIENTATION_PORTRAIT && !isTablet()) {
                        Column(modifier = Modifier.fillMaxWidth()) {
                            Text(
                                modifier = Modifier.fillMaxWidth(),
                                text =  stringResource(R.string.wsn_avg_nums_comments),
                                textAlign = TextAlign.Start,
                                style = MaterialTheme.typography.bodyMedium,
                                color = colorScheme.onPrimaryContainer
                            )
                            Row(modifier = Modifier.fillMaxWidth()) {
                                FhcSlider(
                                    modifier = Modifier.align(alignment = Alignment.CenterVertically).width(220.dp),
                                    color = colorScheme.onPrimaryContainer,
                                    value = avgNum.toFloat(),
                                    steps = 1,
                                    onValueChange = { onAvgNum(it.toInt()) },
                                    valueRange = 4f..6f,
                                )
                                Text(
                                    modifier = Modifier.align(alignment = Alignment.CenterVertically).wrapContentWidth().widthIn(min = 24.dp)
                                        .padding(start = 4.dp),
                                    textAlign = TextAlign.End, text = avgNum.toString(), maxLines = 1, fontWeight = FontWeight.ExtraBold,
                                    color = colorScheme.onPrimaryContainer
                                )
                            }
                        }

                        HorizontalDivider(
                            modifier = Modifier.padding(vertical = 8.dp),
                            thickness = DividerDefaults.Thickness,
                            color = DividerDefaults.color
                        )
                        Column(modifier = Modifier.fillMaxWidth()) {
                            Text(
                                modifier = Modifier.fillMaxWidth(),
                                text =  stringResource(R.string.wsn_rssi_minutes_comments),
                                textAlign = TextAlign.Start,
                                style = MaterialTheme.typography.bodyMedium,
                                color = colorScheme.onPrimaryContainer
                            )

                            Row(modifier = Modifier.fillMaxWidth()) {
                                FhcSlider(
                                    modifier = Modifier.align(alignment = Alignment.CenterVertically).width(220.dp),
                                    color = colorScheme.onPrimaryContainer,
                                    value = rssiMins.toFloat(),
                                    steps = 8,
                                    onValueChange = { onRssiMins(it.toInt()) },
                                    valueRange = 1f..10f,
                                )
                                Text(
                                    modifier = Modifier.align(alignment = Alignment.CenterVertically).wrapContentWidth().widthIn(min = 24.dp)
                                        .padding(start = 4.dp),
                                    textAlign = TextAlign.End, text = rssiMins.toString(), maxLines = 1, fontWeight = FontWeight.ExtraBold,
                                    color = colorScheme.onPrimaryContainer
                                )
                            }
                        }

                        HorizontalDivider(
                            modifier = Modifier.padding(vertical = 8.dp),
                            thickness = DividerDefaults.Thickness,
                            color = DividerDefaults.color
                        )
                    }else{
                        Row(modifier = Modifier.fillMaxWidth()) {
                            Text(
                                modifier = Modifier.align(alignment=Alignment.CenterVertically).widthIn(min = 120.dp).weight(1f),
                                text =  stringResource(R.string.wsn_avg_nums_comments),
                                textAlign = TextAlign.Start,
                                style = MaterialTheme.typography.bodyMedium,
                                color = colorScheme.onPrimaryContainer
                            )
                            FhcSlider(
                                modifier = Modifier.align(alignment=Alignment.CenterVertically).width(220.dp),
                                color= colorScheme.onPrimaryContainer,
                                value = avgNum.toFloat(),
                                steps = 1,
                                onValueChange = { onAvgNum(it.toInt()) },
                                valueRange = 4f..6f,
                            )
                            Text(modifier = Modifier.align(alignment=Alignment.CenterVertically).wrapContentWidth().widthIn(min = 24.dp).padding(start = 4.dp),
                                textAlign = TextAlign.End, text = avgNum.toString(), maxLines = 1,fontWeight = FontWeight.ExtraBold,
                                color = colorScheme.onPrimaryContainer)
                        }

                        HorizontalDivider(
                            modifier = Modifier.padding(vertical = 8.dp),
                            thickness = DividerDefaults.Thickness,
                            color = DividerDefaults.color
                        )
                        Row(modifier = Modifier.fillMaxWidth()) {
                            Text(
                                modifier = Modifier.align(alignment=Alignment.CenterVertically).widthIn(min = 120.dp).weight(1f),
                                text =  stringResource(R.string.wsn_rssi_minutes_comments),
                                textAlign = TextAlign.Start,
                                style = MaterialTheme.typography.bodyMedium,
                                color = colorScheme.onPrimaryContainer
                            )
                            FhcSlider(
                                modifier = Modifier.align(alignment=Alignment.CenterVertically).width(220.dp),
                                color= colorScheme.onPrimaryContainer,
                                value = rssiMins.toFloat(),
                                steps = 8,
                                onValueChange = { onRssiMins(it.toInt()) },
                                valueRange = 1f..10f,
                            )
                            Text(modifier = Modifier.align(alignment=Alignment.CenterVertically).wrapContentWidth().widthIn(min = 24.dp).padding(start = 4.dp),
                                textAlign = TextAlign.End, text = rssiMins.toString(), maxLines = 1, fontWeight = FontWeight.ExtraBold,
                                color = colorScheme.onPrimaryContainer)
                        }

                        HorizontalDivider(
                            modifier = Modifier.padding(vertical = 8.dp),
                            thickness = DividerDefaults.Thickness,
                            color = DividerDefaults.color
                        )
                    }

                }
            }

        }
    }
}

@Composable
private fun CardItemRow(label: String, value: String) {
    Row(
        modifier = Modifier.fillMaxWidth(),
        horizontalArrangement = Arrangement.SpaceBetween
    ) {
        Text(
            modifier = Modifier.wrapContentWidth().widthIn(min = 120.dp),
            text = label,
            style = MaterialTheme.typography.bodyMedium,
            color = colorScheme.onPrimaryContainer
        )
        Text(
            text = value,
            style = MaterialTheme.typography.bodySmall,
            color = colorScheme.onPrimaryContainer.copy(alpha = 0.8f),
            textAlign = TextAlign.End
        )
    }
}


@Composable
private fun LanguageItemRow(label:String, language: String) {
    val currentLocale = LocalManager.currentLocale.collectAsStateWithLifecycle()
    val isSystemLocale = LocalManager.isSystemLocale.collectAsStateWithLifecycle()

    val context = LocalContext.current
    Timber.i("LanguageItemRow  :   %s , %s , %s", label, currentLocale.value.language, language)
    Row(
        modifier = Modifier.fillMaxWidth().clickable(
            onClick = {
                Timber.i("LanguageItemRow  onClick :   %s , %s , %s", label, currentLocale.value.language, language)
                LocalManager.setAppLocale(context = context, languageTag = language)
            }
        ),
        horizontalArrangement = Arrangement.SpaceBetween
    ) {
        Text(
            modifier = Modifier.wrapContentWidth().widthIn(min = 120.dp),
            text = label,
            style = MaterialTheme.typography.bodyMedium,
            color = colorScheme.onPrimaryContainer
        )
        if( isSystemLocale.value){
            if(language.isEmpty()){
                Icon(
                    modifier = Modifier.size(20.dp),
                    imageVector = Icons.Default.Check,
                    contentDescription = null,
                    tint = Color.White
                )
            }
        }else {
            if(currentLocale.value.language == language){
                Icon(
                    modifier = Modifier.size(20.dp),
                    imageVector = Icons.Default.Check,
                    contentDescription = null,
                    tint = Color.White
                )
            }
        }
    }
}


//
//
//@Composable
//fun LanguageSwitchMenu(
//    expanded: MutableState<Boolean> = remember { mutableStateOf(false) },
//    onSelected: ((locale: Locale) -> Unit)? = null
//) {
//    val currentLocale = LocalManager.currentLocale.collectAsStateWithLifecycle()
//    val context = LocalContext.current
//    if(onSelected == null){
//        IconButton(onClick = {
//            if(currentLocale.value.language == Locale.JAPANESE.language) LocalManager.setAppLocale(context,Locale.ENGLISH.language)
//            else LocalManager.setAppLocale(context,Locale.JAPANESE.language)
//        }) {
//            Icon(
//                painterResource(id = if(currentLocale.value.language == Locale.JAPANESE.language)  R.drawable.ic_lang_jp_en  else R.drawable.ic_lang_en_jp),
//                null
//            )
//        }
//        return
//    }
//    TopAppBarDropdownMenu(
//        expanded,
//        iconContent = {
//            Icon(
//                Icons.Outlined.ArrowDropDown, null,
//                modifier = Modifier.padding(end = 6.dp).size(32.dp), tint = Color.White
//            )
//        }
//    ) { closeMenu ->
//        DropdownMenuItem(
//            modifier = Modifier.wrapContentSize(),
//            onClick = {
//                onSelected(Locale.ENGLISH)
//                closeMenu()
//            },
//            text = {
//
//                Text(text = ENGLISH)
//
//
//            },
//
//            trailingIcon = {
//                if(currentLocale.value.language == Locale.ENGLISH.language){
//                    Icon(
//                        modifier = Modifier.size(20.dp),
//                        imageVector = Icons.Default.Check,
//                        contentDescription = null,
//                        tint = Color.Blue
//                    )
//                }
//            },
//            contentPadding = MenuDefaults.DropdownMenuItemContentPadding,
//        )
//
//        DropdownMenuItem(
//            modifier = Modifier.wrapContentSize(),
//            onClick = {
//                onSelected(Locale.JAPANESE)
//                closeMenu()
//            },
//            text = {Text(text =JAPANESE)},
//
//            trailingIcon = {
//                if(currentLocale.value.language == Locale.JAPANESE.language){
//                    Icon(
//                        modifier = Modifier.size(20.dp),
//                        imageVector = Icons.Default.Check,
//                        contentDescription = null,
//                        tint = Color.Blue
//                    )
//                }
//            },
//            contentPadding = MenuDefaults.DropdownMenuItemContentPadding,
//        )
//    }
//}



@Preview(showBackground = true,widthDp = 800)
@Composable
private fun AppSection(isLogEnabled: Boolean = false, onEnableLog: (Boolean) -> Unit ={},  intentDir: Intent? = null) {
    val isExpanded = remember { mutableStateOf(true) }
    val rotation = remember { Animatable(0f) }

    // 动画启动副作用
    LaunchedEffect(isExpanded.value) {
        val targetRotation = if (isExpanded.value) 180f else 0f
        rotation.animateTo(
            targetRotation,
            animationSpec = tween(durationMillis = 300)
        ) {
        }
    }


    Box(modifier = Modifier.fillMaxWidth()){
        Card(
            colors = CardDefaults.cardColors(containerColor = Color.White.copy(alpha = 0.15f),
                contentColor = Color.White),
            shape = RoundedCornerShape(12.dp), // 自定义圆角大小
            modifier = Modifier.fillMaxWidth().padding(spaceP)
        ) {
            Row(
                modifier = Modifier.padding(top = 10.dp, bottom = 10.dp, start = startP,end = 6.dp).clickable(
                    onClick = {isExpanded.value = !isExpanded.value}
                ),
                verticalAlignment = Alignment.CenterVertically
            ) {
//                CircleTextView(text = "RSSI", sizeDp = widthP, backgroundColor = colorScheme.onPrimaryContainer.copy(alpha = 0.3f))
                Icon(
                    Icons.Outlined.Apps, null, Modifier.size(widthP), colorScheme.primary
                )
                Spacer(modifier = Modifier.width(spaceP))
                Row(modifier = Modifier.fillMaxWidth().weight(1f)) {
                    Text(
                        modifier = Modifier.weight(1f).align(alignment = Alignment.CenterVertically),
                        text = stringResource(R.string.wsn_app_setting),
                        style = MaterialTheme.typography.titleSmall,
                        color = colorScheme.onPrimaryContainer,
                        fontWeight = FontWeight.ExtraBold
                    )
                }
                IconButton(
                    modifier = Modifier.height(widthP).align(alignment = Alignment.CenterVertically),
                    onClick = {
                        isExpanded.value = !isExpanded.value
                    }) {
                    Icon(Icons.Outlined.ArrowDropDown, null, tint = Color.White, modifier = Modifier.size(32.dp).graphicsLayer {
                        rotationZ = rotation.value
                    })
                }
            }
            AnimatedVisibility(
                visible = isExpanded.value,
                enter = expandVertically() + fadeIn(),
                exit = shrinkVertically() + fadeOut()
            ) {
                HorizontalDivider(modifier = Modifier.padding(start = 16.dp, end = 16.dp))
                Column(modifier = Modifier.padding(start = rightP, end = rightP, top = 16.dp, bottom = 16.dp)) {
                    Row(modifier = Modifier.fillMaxWidth()) {
                        Text(
                            modifier = Modifier.align(alignment=Alignment.CenterVertically).widthIn(min = 120.dp).weight(1f),
                            text =  stringResource(R.string.wsn_app_setting_log),
                            textAlign = TextAlign.Start,
                            style = MaterialTheme.typography.bodyMedium,
                            color = colorScheme.onPrimaryContainer
                        )
                        Switch(
                            modifier = Modifier.wrapContentSize(),
                            checked = isLogEnabled,
                            onCheckedChange = {
                                onEnableLog(it)
                            },
                            colors = SwitchDefaults.colors(
                                checkedTrackColor = colorScheme.primary
                            )
                        )
                    }

                    HorizontalDivider(
                        modifier = Modifier.padding(vertical = 8.dp),
                        thickness = DividerDefaults.Thickness,
                        color = DividerDefaults.color
                    )
                }
            }
        }

//        if(intentDir !=null && isExpanded.value){
//            Box(modifier = Modifier.align(Alignment.BottomEnd).wrapContentSize().padding(end = 20.dp, bottom = 32.dp)) {
//                IconButton(
//                    modifier = Modifier.height(widthP),
//                    onClick = {
//                        try {
//                            context.startActivity(intentDir)
//                        } catch (e: ActivityNotFoundException) {
//                            Toast.makeText(context, "Cannot find file manager Application", Toast.LENGTH_SHORT).show()
////                        ToastyShow(msgRes = uiData.toastMsgId!!,uiData.toastMsgArgs, showAfter = {
////                            viewModel.toastMessageClear()
////                        })
//                        }
//                    }) {
//                    Icon(Icons.Outlined.Folder, null, modifier = Modifier.size(32.dp))
//                }
//            }
//        }

    }
}
